package com.xjoyt.pay.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
//import org.apache.http.params.CoreConnectionPNames;



public class HttpClientUtil {

	public static String sendget(String webUrl,String xmlFile,String charset){
		StringBuffer sBuffer = new StringBuffer();
		// 閺嬪嫰锟紿ttpClient閻ㄥ嫬鐤勬笟锟�
		HttpClient httpClient = new HttpClient();
		GetMethod  getMethod = new GetMethod(webUrl+"?"+xmlFile);
		System.out.println("get addr============"+webUrl+"?"+xmlFile);
		getMethod.setRequestHeader("Content-Type","application/json");  
		getMethod.setRequestHeader("charset",charset);
	//WW	getMethod.setRequestEntity(new StringRequestEntity(xmlFile, "application/json", charset));

		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
//		getMethod.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000*100);
//		getMethod.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000*100);
		try {
			int statusCode = httpClient.executeMethod(getMethod);
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: " + getMethod.getStatusLine());
			}
			byte[] responseBody = getMethod.getResponseBody();
			sBuffer.append(new String(responseBody, "utf-8"));
		} catch (HttpException e) {
			System.out.println("Please check your provided http address!");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			getMethod.releaseConnection();
		}
		return sBuffer.toString();

	}
	public static String send(String webUrl, String xmlFile, String charset) throws UnsupportedEncodingException {
		StringBuffer sBuffer = new StringBuffer();
		// 閺嬪嫰锟紿ttpClient閻ㄥ嫬鐤勬笟锟�
		HttpClient httpClient = new HttpClient();
		// 閸掓稑缂揚OS閺傝纭堕惃鍕杽娓氾拷
		PostMethod postMethod = new PostMethod(webUrl);
		postMethod.setRequestHeader("Content-Type","application/json");  
		postMethod.setRequestHeader("charset",charset);
		postMethod.setRequestEntity(new StringRequestEntity(xmlFile, "application/json", charset));
		postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
//		postMethod.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000*100);
//		postMethod.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000*100);
		try {
			// 閹笛嗩攽getMethod
			int statusCode = httpClient.executeMethod(postMethod);
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: " + postMethod.getStatusLine());
			}
			// 鐠囪褰囬崘鍛啇
			byte[] responseBody = postMethod.getResponseBody();
			// 婢跺嫮鎮婇崘鍛啇
			sBuffer.append(new String(responseBody, "utf-8"));
		} catch (HttpException e) {
			// 閸欐垹鏁撻懛鏉戞嚒閻ㄥ嫬绱撶敮闈╃礉閸欘垵鍏橀弰顖氬礂鐠侇喕绗夌�佃鍨ㄩ懓鍛扮箲閸ョ偟娈戦崘鍛啇閺堝妫舵０锟�
			System.out.println("Please check your provided http address!");
			e.printStackTrace();
		} catch (IOException e) {
			// 閸欐垹鏁撶純鎴犵捕瀵倸鐖�
			e.printStackTrace();
		} finally {
			// 闁插﹥鏂佹潻鐐村复
			postMethod.releaseConnection();
		}
		return sBuffer.toString();
	}
 
	public static String sendPost(String url, Map<String, String> parameters) {
		String result = "";// 返回的结果
		BufferedReader in = null;// 读取响应输入流
		PrintWriter out = null;
		StringBuffer sb = new StringBuffer();// 处理请求参数
		String params = "";// 编码之后的参数
		java.net.HttpURLConnection httpConn = null;
		try {
			// 编码请求参数
			if (parameters.size() == 1) {
				for (String name : parameters.keySet()) {
					sb.append(name).append("=").append(java.net.URLEncoder.encode(parameters.get(name).toString(), "UTF-8"));
				}
				params = sb.toString();
			} else {
				for (String name : parameters.keySet()) {
					sb.append(name).append("=").append(java.net.URLEncoder.encode(parameters.get(name).toString(), "UTF-8"))
							.append("&");
				}
				String temp_params = sb.toString();
				params = temp_params.substring(0, temp_params.length() - 1);
			}
			// 创建URL对象
			java.net.URL connURL = new java.net.URL(url);
			// 打开URL连接
			httpConn = (java.net.HttpURLConnection) connURL.openConnection();
			// 设置通用属性
			httpConn.setInstanceFollowRedirects(false);
			httpConn.setRequestProperty("Accept", "*/*");
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
			// 设置POST方式
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			// 获取HttpURLConnection对象对应的输出流
			out = new PrintWriter(httpConn.getOutputStream());
			// 发送请求参数
			out.write(params);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应，设置编码方式
			in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));
			System.out.println("in = "+in);
			
			String line;
			// 读取返回的内容
			while ((line = in.readLine()) != null) {
				result += line;
			
			}
			System.out.println("result = "+result);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}
	
	public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            //建立连接
            URLConnection conn = realUrl.openConnection();
            // 设置参数
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 设置输出
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 读入数据
            out = new PrintWriter(conn.getOutputStream());
            // 输出数据
            out.print(param);
            // flush缓存
            out.flush();
            // 读取返回值BufferedReader
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("POST出异常了===="+e);
            e.printStackTrace();
        }
        //关闭通道
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }    



   
}
